package com.lsj.ssmTest.controller;

import com.lsj.ssmTest.core.config.UploadConfig;
import com.lsj.ssmTest.core.constants.CommonConstants;
import com.lsj.ssmTest.core.entity.AjaxResult;
import com.lsj.ssmTest.core.exception.LoginException;
import com.lsj.ssmTest.model.User;
import com.lsj.ssmTest.service.IUserService;
import lombok.AllArgsConstructor;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * @author Lsj
 * @version 1.0
 * @date 2021/6/29 11:36
 */
@Controller
@RequestMapping("/user")
@AllArgsConstructor
@Log4j
public class UserController {
    private final IUserService userService;
    private final UploadConfig uploadConfig;
    @GetMapping("userList")
    public String list(User user, Model model) {
        List<User> list = userService.list(user);
        model.addAttribute("userList", list);
        System.out.println("进入到userController");
        return "user/userList";
    }

    @PostMapping(value = "login", params = {"username", "password"})
    @ResponseBody
    public AjaxResult<User> login(String username, String password, HttpSession session) throws LoginException {
        User user = userService.login(username, password);
        session.setAttribute(CommonConstants.LOGIN_USER, user);
        return new AjaxResult<>(user);
    }

    @GetMapping(value = "logout")
    public String logout(HttpSession session) throws LoginException {
        session.removeAttribute(CommonConstants.LOGIN_USER);
        return "redirect:/";
    }

    @PostMapping("upload")
    @ResponseBody
    public AjaxResult<String> upload(MultipartFile file) {
        if (file.isEmpty()) {
            return new AjaxResult<>(400, "请选择文件");
        }
        File targetFile = new File(uploadConfig.getUploadPath()+file.getOriginalFilename());
        try {
            file.transferTo(targetFile);
            return new AjaxResult<>(uploadConfig.getUploadPrefix()+file.getOriginalFilename());
        } catch (IOException e) {
            e.printStackTrace();
            return new AjaxResult<>(500, "文件上传失败");
        }
    }

}
